<template>
  <m-window-frame
    :title="title"
    style="height: 100%"
    class="v-vire-params-window"
    :okLoading="okLoading"
    @cancel="handleCancel"
    @ok="handleSave"
  >
    <div class="v-vire-params-window-container">
      <AttrTip
        class="_main-title g-flex-0"
        :propertyGroupConfig="attrInfo"
        type=""
      ></AttrTip>
      <div class="form-container">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          :hide-required-asterisk="true"
        >
          <el-form-item
            v-for="item in dataList"
            :key="item.id"
            :label="item.name"
            :prop="item.id"
          >
            <el-input
              v-model="ruleForm[item.id]"
              :placeholder="'请输入' + item.name"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import { ref, watch, reactive, computed, onMounted } from "vue";
import { Params, CloseData } from "./index";
import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import AttrTip from "@/common/attrTip/AttrTip.vue";
import { archService } from "@/mdesign-lib/mdesign-app.umd.js";

interface Param {
  id: string;
  type: 0 | 1 | 2 | 3;
  name: string;
  value: string | number;
  parentId: string;
}

const ruleFormRef = ref<FormInstance>();
const title = ref("");
const elementName = ref("");
const projectId = ref("");
const modelId = ref("");
const okLoading = ref(false);
const dataList = ref<Param[]>([]);
const attrInfo = computed<{ name: string; description: string; icon: string }>(() => {
  return {
    name: "参数说明",
    description: `当前参数为${elementName.value}行为所对应的参数。`,
    icon: "statics/icons/attrTip/vireParams.svg"
  };
});

const ruleForm = reactive<Record<string, string | number>>({});
const rules = reactive<FormRules<Record<string, string | number>>>({});

const route = useRoute();
watch(
  () => route.fullPath,
  () => {
    const routeQuery = route.query as unknown;
    const query = routeQuery as Params;
    elementName.value = query.elementName;
    title.value = elementName.value + "参数";
    projectId.value = query.projectId;
    modelId.value = query.modelId;
  },
  { immediate: true }
);

onMounted(() => {
  getParams();
});

const getParams = async () => {
  const data = (await archService.getVireVariables(projectId.value, modelId.value)) as Param[];
  dataList.value = data.filter(item => item.type !== 0);
  dataList.value.forEach(item => {
    ruleForm[item.id] = item.value;
    const rule: any[] = [
      { required: true, message: `请输入${item.name}` },
      { validator: validator, type: item.type }
    ];
    rules[item.id] = rule;
  });
};

function validator(rule: any, value: string, callback: any) {
  const { type } = rule;
  if (type === 1) {
    const pattern = /^-?\d+$/;
    if (!pattern.test(value)) {
      callback(new Error("请输入一个整数"));
    }
  } else if (type === 2) {
    const pattern = /^-?\d+(\.\d+)?$/;
    if (!pattern.test(value)) {
      callback(new Error("请输入一个数字"));
    }
  }
}

const handleSave = async () => {
  const valid = ruleFormRef.value?.validate();
  if (!valid) return;
  okLoading.value = true;
  console.log("ruleForm", ruleForm);
  const queue: Promise<void>[] = [];
  dataList.value.forEach(item => {
    const newValue = ruleForm[item.id];
    if (item.value !== newValue) {
      queue.push(archService.updateVireVariables(projectId.value, modelId.value, item.id, newValue as string, item.parentId));
    }
  });
  await Promise.all(queue).finally(() => (okLoading.value = false));
  handleclose({ success: true });
};

function handleclose(data: CloseData) {
  ipcWindowUtil.closeWindow(data);
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
.v-vire-params-window {
  .v-vire-params-window-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    .form-container {
      flex: 1;
      overflow: auto;
      padding: 24px 32px;
    }
    .el-form {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
    }
    .el-form-item {
      width: 47%;
      height: 32px;
      margin-bottom: 12px;
      .el-form-item__label {
        padding-right: 0;
        line-height: 32px;
        color: #000;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .el-form-item__label-wrap {
        margin-right: 15px;
      }
      .el-input-group__append {
        border-radius: 0;
        background: #f2f2f2;
        width: 32px;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .el-input__wrapper {
        border: 1px solid rgba(0, 0, 0, 0.15);
        box-shadow: none;
      }
      .el-select {
        width: 100%;
      }
      .el-button {
        border-color: rgba(0, 0, 0, 0.15);
        padding: 8px;
        border-radius: 0;
        &:hover {
          border-color: var(--md-primary-color);
        }
      }
    }
  }
}
</style>
